package edu.nf.ch05.service.impl;

import edu.nf.ch05.entity.Goods;
import edu.nf.ch05.entity.Order;
import edu.nf.ch05.mapper.GoodsMapper;
import edu.nf.ch05.mapper.OrderMapper;
import edu.nf.ch05.service.DeckillService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author gjh
 * @Date 2025/9/28
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class DeskillServiceImpl implements DeckillService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final GoodsMapper goodsMapper;
    private final OrderMapper orderMapper;

    @PostConstruct
    public void initGoodCache(){
        List<Goods> goodsList = goodsMapper.findAll();
        for (Goods goods : goodsList) {
            // 缓存商品ID == 库存数量
            redisTemplate.opsForValue().set("stock:" + goods.getGoodId(), goods.getStock());
        }
    }

    @Override
    public void decrStock(int gid) {
        Long stock = redisTemplate.opsForValue().decrement("stock:" + gid);
        if(stock != null && stock >= 0){
            Order order = new Order();
            order.setOrderId(gid);
            order.setGoodsId(gid);
            order.setOrderStatus(0);
            order.setUserId(1);
            orderMapper.addOrder(order);
            goodsMapper.decrStock(gid);
        } else {
            // 回滚（因为 decrement 可能会到 -1）
            redisTemplate.opsForValue().increment("stock:" + gid);
            throw new RuntimeException("库存不足");
        }
    }
}
